package cn.sfa.controller.manage;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialException;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.sfa.common.pagination.Pagination;
import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.DateUtil;
import cn.sfa.common.utils.FormValidate;
import cn.sfa.common.utils.WebInitBinderContoller;
import cn.sfa.entity.affixItem.SaleAffixItem;
import cn.sfa.entity.meeting.SaleMeeting;
import cn.sfa.entity.users.Branch;
import cn.sfa.entity.users.SaleUsersLogin;
import cn.sfa.service.affix.AffixService;
import cn.sfa.service.login.LoginService;
import cn.sfa.service.manage.ManageMeetingService;
import cn.sfa.service.meeting.MeetingService;

/**
 * 早会管理
 * 
 * @ClassName：ManageMeetingController
 * @Description：TODO
 * @author：LiXiang
 * @date：2012-4-20 上午09:18:10
 */
@Controller
@RequestMapping("manage/meetings/index")
public class ManageMeetingController extends WebInitBinderContoller {

	Logger log = LoggerFactory.getLogger(ManageMeetingController.class);
	@Autowired
	LoginService loginService;
	@Autowired
	AffixService affixService;
	@Autowired
	ManageMeetingService meetingService;

	@Autowired
	MeetingService meetingServiceInner;

	private Pagination pagination;// 分页

	public Pagination getPagination() {
		return pagination;
	}

	public void setPagination(Pagination pagination) {
		this.pagination = pagination;
	}

	/**
	 * 管理早会页面
	 * 
	 * @param saleMeeting
	 * @return String
	 */
	@RequestMapping(value = "/getmeetings")
	public String managesNews(
			@RequestParam(value = "currentPage", required = false) String currentPage,
			SaleMeeting saleMeeting,
			HttpServletRequest request,
			ModelMap map,
			@RequestParam(value = "beginCreateDate", required = false) String beginCreateDate,
			@RequestParam(value = "endCreateDate", required = false) String endCreateDate) {

		List<Branch> branchs = loginService.getAllBranchs();
		request.setAttribute("branchs", branchs);

		int pageIndex;
		try {
			pageIndex = Integer.valueOf(currentPage);
		} catch (Exception ex) {
			pageIndex = 1;
		}

		Pagination pagination = null;
		pagination = meetingService.searchMeetings(
				pageIndex,
				10,
				request.getContextPath()
						+ "/manage/meetings/index/getmeetings?"
						+ "&meetingTitle="
						+ CommonUtil.jugeAndFixNull(saleMeeting
								.getMeetingTitle())
						+ "&meetingContent="
						+ CommonUtil.jugeAndFixNull(saleMeeting
								.getMeetingContent())
						+ "&beginCreateDate="
						+ (CommonUtil.isEmpty(beginCreateDate) ? ""
								: beginCreateDate)
						+ "&endCreateDate="
						+ (CommonUtil.isEmpty(endCreateDate) ? ""
								: endCreateDate), saleMeeting, (CommonUtil.isEmpty(beginCreateDate) ? ""
										: beginCreateDate), (CommonUtil.isEmpty(endCreateDate) ? ""
												: endCreateDate));

		map.put("pagination", pagination);
		map.put("meetingTitle", saleMeeting.getMeetingTitle());
		map.put("meetingStatus", saleMeeting.getMeetingStatus());
		map.put("meetingMaster", saleMeeting.getMeetingMaster());
		map.put("meetingContent", saleMeeting.getMeetingContent());
		map.put("beginCreateDate", CommonUtil.isEmpty(beginCreateDate) ? ""
				: beginCreateDate);
		map.put("endCreateDate", CommonUtil.isEmpty(endCreateDate) ? ""
				: endCreateDate);
		map.put("page", pageIndex);

		return "/manage/meetings/getmeetings";
	}

	/**
	 * 删除早会 TODO
	 * 
	 * @author: LiXiang
	 * @param response
	 * @param saleMeetingId
	 * @throws IOException
	 */
	@RequestMapping("/delete/{saleMeetingId}")
	public void delete(HttpServletResponse response, @PathVariable("saleMeetingId") String saleMeetingId) throws IOException {
		response.setContentType("text/json");
		PrintWriter out = response.getWriter();
		boolean flag = meetingService.deleteMeetingById(saleMeetingId);
		JSONObject jo = new JSONObject();
		jo.put("isDel", flag);
		out.print(jo);
		out.flush();
		out.close();
	}

	/**
	 * 审核早会 TODO
	 * 
	 * @author: LiXiang
	 * @param request
	 * @param saleNewsId
	 * @param map
	 * @throws IOException
	 */
	@RequestMapping(value = ("/verify"))
	public void verify(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws IOException {
		PrintWriter out = response.getWriter();
		String saleMeetingId = request.getParameter("saleMeetingId");
		String meetingStatus = request.getParameter("meetingStatus");
		String returnStatus = "";
		if ("APPLYSTATUS_2".equals(meetingStatus) || "APPLYSTATUS_4".equals(meetingStatus)) {
			meetingStatus = "APPLYSTATUS_3";
			returnStatus = "y";
		} else if ("APPLYSTATUS_3".equals(meetingStatus)) {
			meetingStatus = "APPLYSTATUS_4";
			returnStatus = "n";
		}
		meetingService.updateMeetingStatus(saleMeetingId, meetingStatus);
		JSONObject jo = new JSONObject();
		jo.put("returnStatus", returnStatus);
		out.print(jo);
		out.flush();
		out.close();
	}

	/**
	 * 查看早会
	 * 
	 * @return String
	 * @throws SQLException
	 * @throws SerialException
	 */
	@RequestMapping(value = ("/view"))
	public String view(HttpServletRequest request, ModelMap map, HttpServletResponse response) throws Exception {
		String saleMeetingId = request.getParameter("saleMeetingId");
		SaleMeeting saleMeeting = meetingService.getMeeting(saleMeetingId);
		map.put("saleMeeting", saleMeeting);
		// 附件列表
		List<SaleAffixItem> affixList = affixService.getAffix("SALEMEETING", saleMeetingId);
		map.put("affixList", affixList);
		return "/manage/meetings/view";
	}

	// /////////////////////////Inner begin////////////

	/**
	 * 转到添加早会页面
	 * 
	 * @param saleNews
	 * @return String
	 */
	@RequestMapping("/inner/addmeeting")
	public String addMeeting(SaleMeeting saleMeeting, HttpServletRequest request) {
		return "/manage/meetings/inner/addmeeting";
	}

	@RequestMapping("/inner/validate")
	public void validate(SaleMeeting saleMeeting, HttpServletRequest request, ModelMap map, HttpServletResponse response) throws Exception {
		int count = 0;
		String meetingTitle = "";
		String meetingContent = "";
		// 表单验证
		if (CommonUtil.isEmpty(saleMeeting.getMeetingTitle())) {
			meetingTitle = "早会标题不能为空！";
			count = count + 1;
		} else if (CommonUtil.isEmpty(saleMeeting.getMeetingContent())) {
			meetingContent = "早会内容不能为空！";
			count = count + 1;
		} else if (saleMeeting.getMeetingTitle().length() < 6 || saleMeeting.getMeetingTitle().length() > 50) {
			meetingTitle = "早会标题长度必须在6到50位";
			count = count + 1;

		} else if (saleMeeting.getMeetingContent().length() > 100000) {
			meetingContent = "早会内容长度必须小于100000位";
			count = count + 1;
		}

		PrintWriter out = response.getWriter();
		boolean result = count == 0;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		request.setCharacterEncoding("UTF-8");


		JSONObject temp = new JSONObject();
		temp.put("result", result);
		temp.put("meetingTitle", meetingTitle);
		temp.put("meetingContent", meetingContent);


		out.print(temp.toString());
		out.flush();
		out.close();
	}

	/**
	 * 添加早会
	 * 
	 * @param saleNews
	 * @return String
	 * @throws SQLException
	 * @throws SerialException
	 */
	@RequestMapping("/inner/add")
	public void add(SaleMeeting saleMeeting, HttpServletRequest request, ModelMap map, HttpServletResponse response, @RequestParam(value = "affixStr", required = false) String affixStr, @RequestParam(value = "mCount", required = false) String mcount, @RequestParam(value = "sDate", required = false) String sDate, @RequestParam(value = "eDate", required = false) String eDate) throws Exception {

		PrintWriter out = response.getWriter();


		int count = 0;
		String meetingTitle = "";
		String meetingContent = "";
		String add = "";
		String startDate = "";
		String endDate = "";
		String meetingCount = "";
		if (CommonUtil.isEmpty(saleMeeting.getMeetingTitle())) {
			meetingTitle = "早会标题不能为空！";
			count = count + 1;
		} else if (CommonUtil.isEmpty(saleMeeting.getMeetingContent())) {
			meetingContent = "早会内容不能为空！";
			count = count + 1;
		} else if (CommonUtil.isEmpty(mcount)) {
			meetingCount = "早会人数不能为空！";
			count = count + 1;
		} else if (CommonUtil.isEmpty(sDate)) {
			startDate = "早会开始时间不能为空！";
			count = count + 1;
		} else if (CommonUtil.isEmpty(eDate)) {
			endDate = "早会结束时间不能为空！";
			count = count + 1;
		} else if (saleMeeting.getMeetingTitle().length() < 6 || saleMeeting.getMeetingTitle().length() > 50) {
			meetingTitle = "早会标题长度必须在6到50位";
			count = count + 1;
		} else if (saleMeeting.getMeetingContent().length() > 100000) {
			meetingContent = "早会内容长度必须小于100000位";
			count = count + 1;
		} else if (!FormValidate.isNumber(mcount)) {
			meetingCount = "早会人数必须为数字";
			count = count + 1;
		} else if (DateUtil.stringToDate2(sDate).getTime() - (new Date()).getTime() > 0) {
			startDate = "早会开始时间必须小于创建时间！";
			count = count + 1;
		} else if (DateUtil.stringToDate2(eDate).getTime() - DateUtil.stringToDate2(sDate).getTime() < 0) {
			endDate = "早会结束时间必须大于早会开始时间！";
			count = count + 1;
		}
		boolean result = count == 0;
		SaleUsersLogin user = (SaleUsersLogin) request.getSession().getAttribute("user");
		if (result) {
			saleMeeting.setCreateUid(user.getSaleUsersLoginId());
			saleMeeting.setCreateDate(new Date());
			saleMeeting.setUpdateDate(new Date());
			saleMeeting.setStartDate(DateUtil.stringToDate2(sDate));
			saleMeeting.setEndDate(DateUtil.stringToDate2(eDate));
			saleMeeting.setUpdateId(user.getSaleUsersLoginId());
			saleMeeting.setMeetingMaster(user.getSaleUsersLoginId());
			saleMeeting.setMeetingStatus("APPLYSTATUS_3");// 未申请状态
			saleMeeting.setMeetingCount(Integer.parseInt(mcount));
			boolean flag = meetingServiceInner.addMeeting(saleMeeting,"Y");
			if (flag) {
				try {
					// 保存附件
					affixService.saveAffix(affixStr, "SALEMEETING", saleMeeting.getSaleMeetingId());
					add = "添加早会成功！";
				} catch (Exception e) {
					add = "添加早会失败！";
				}

				map.put("meeting", saleMeeting);
			} else {
				add = "添加早会失败！";
			}
		}

		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		request.setCharacterEncoding("UTF-8");


		JSONObject temp = new JSONObject();
		temp.put("result", result);
		temp.put("add", add);
		temp.put("meetingTitle", meetingTitle);
		temp.put("meetingContent", meetingContent);
		temp.put("startDate", startDate);
		temp.put("endDate", endDate);
		temp.put("meetingCount", meetingCount);

		out.print(temp.toString());
		out.flush();
		out.close();
	}

	/**
	 * 管理早会页面
	 * 
	 * @param saleNews
	 * @return String
	 */
	@RequestMapping(value = "/inner/getmeetings")
	public String manageNews(
			@RequestParam(value = "currentPage", required = false) String currentPage,
			SaleMeeting saleMeeting,
			HttpServletRequest request,
			ModelMap map,
			@RequestParam(value = "beginCreateDate", required = false) String beginCreateDate,
			@RequestParam(value = "endCreateDate", required = false) String endCreateDate) {
		int pageIndex;
		try {
			pageIndex = Integer.valueOf(currentPage);
		} catch (Exception ex) {
			pageIndex = 1;
		}

		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");
		Pagination pagination = null;
		pagination = meetingServiceInner
				.searchMeetings(
						pageIndex,
						10,
						request.getContextPath()
								+ "/manage/meetings/index/inner/getmeetings?"
								+ "meetingTitle="
								+ CommonUtil.jugeAndFixNull(saleMeeting
										.getMeetingTitle())
								+ "&meetingContent="
								+ CommonUtil.jugeAndFixNull(saleMeeting
										.getMeetingContent())
								+ "&masterName="
								+ CommonUtil.jugeAndFixNull(saleMeeting
										.getMasterName())
								+ "&meetingStatus="
								+ CommonUtil.jugeAndFixNull(saleMeeting
										.getMeetingStatus())
								+ "&beginCreateDate="
								+ (CommonUtil.isEmpty(beginCreateDate) ? ""
										: beginCreateDate)
								+ "&endCreateDate="
								+ (CommonUtil.isEmpty(endCreateDate) ? ""
										: endCreateDate), saleMeeting, user
								.getSaleUsersLoginId(), DateUtil
								.stringToDate2(beginCreateDate), DateUtil
								.stringToDate2(endCreateDate));

		map.put("pagination", pagination);
		map.put("meetingTitle", saleMeeting.getMeetingTitle());
		map.put("meetingContent", saleMeeting.getMeetingContent());
		map.put("masterName", saleMeeting.getMasterName());
		map.put("meetingStatus", saleMeeting.getMeetingStatus());
		map.put("beginCreateDate", CommonUtil.isEmpty(beginCreateDate) ? ""
				: beginCreateDate);
		map.put("endCreateDate", CommonUtil.isEmpty(endCreateDate) ? ""
				: endCreateDate);
		map.put("page", pageIndex);

		return "/manage/meetings/inner/getmeetings";
	}

	@RequestMapping("/inner/delete/{saleMeetingId}")
	public void delete(HttpServletRequest request, HttpServletResponse response, @PathVariable("saleMeetingId") String saleMeetingId) throws IOException {
		response.setContentType("text/json");
		PrintWriter out = response.getWriter();
		SaleMeeting meeting = meetingServiceInner.getMeeting(saleMeetingId);
		if (!"APPLYSTATUS_2".equals(meeting.getMeetingStatus()))// 只有正在审核状态不让删除
		{
			boolean flag = meetingServiceInner.deleteMeetingById(saleMeetingId);
			JSONObject jo = new JSONObject();
			jo.put("isDel", flag);
			out.print(jo);
			out.flush();
			out.close();
		}
	}

	/**
	 * 转到编辑页面
	 * 
	 * @param request
	 * @param saleMeetingId
	 * @param map
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = ("/updatemeeting/{saleMeetingId}"))
	public String updatenews(HttpServletRequest request, @PathVariable("saleMeetingId") String saleMeetingId, ModelMap map) throws IOException {
		SaleMeeting meeting = meetingServiceInner.getMeeting(saleMeetingId);
		request.setAttribute("meeting", meeting);
		// 附件列表
		List<SaleAffixItem> affixList = affixService.getAffix("SALEMEETING", saleMeetingId);
		map.put("affixList", affixList);
		request.setAttribute("saleMeetingId", saleMeetingId);
		return "/manage/meetings/inner/updatemeeting";
	}

	/**
	 * 编辑早会
	 * 
	 * @param saleNews
	 * @return String
	 * @throws SQLException
	 * @throws SerialException
	 */
	@RequestMapping(value = ("/inner/edit"))
	public void update(SaleMeeting saleMeeting, HttpServletRequest request, ModelMap map, @RequestParam(value = "affixStr", required = false) String affixStr, // 附件列表
			@RequestParam(value = "mCount", required = false) String mcount, HttpServletResponse response, @RequestParam(value = "sDate", required = false) String sDate, @RequestParam(value = "eDate", required = false) String eDate) throws Exception {
		String saleMeetingId = request.getParameter("saleMeetingId");

		int count = 0;
		String meetingTitle = "";
		String meetingContent = "";
		String add = "";
		String startDate = "";
		String endDate = "";
		String meetingCount = "";
		SaleMeeting meeting = meetingServiceInner.getMeeting(saleMeetingId);
		if (CommonUtil.isEmpty(saleMeeting.getMeetingTitle())) {
			meetingTitle = "早会标题不能为空！";
			count = count + 1;
		} else if (CommonUtil.isEmpty(saleMeeting.getMeetingContent())) {
			meetingContent = "早会内容不能为空！";
			count = count + 1;
		} else if (CommonUtil.isEmpty(mcount)) {
			meetingCount = "早会人数不能为空！";
			count = count + 1;
		} else if (CommonUtil.isEmpty(sDate)) {
			startDate = "早会开始时间不能为空！";
			count = count + 1;
		} else if (CommonUtil.isEmpty(eDate)) {
			endDate = "早会结束时间不能为空！";
			count = count + 1;
		} else if (saleMeeting.getMeetingTitle().length() < 6 || saleMeeting.getMeetingTitle().length() > 50) {
			meetingTitle = "早会标题长度必须在6到50位";
			count = count + 1;
		} else if (saleMeeting.getMeetingContent().length() > 100000) {
			meetingContent = "早会内容长度必须小于100000位";
			count = count + 1;
		} else if (!FormValidate.isNumber(mcount)) {
			meetingCount = "早会人数必须为数字";
			count = count + 1;
		} else if (DateUtil.stringToDate2(sDate).getTime() - (meeting.getCreateDate()).getTime() > 0) {
			startDate = "早会开始时间必须小于创建时间！";
			count = count + 1;
		} else if (DateUtil.stringToDate2(eDate).getTime() - DateUtil.stringToDate2(sDate).getTime() < 0) {
			endDate = "早会结束时间必须大于早会开始时间！";
			count = count + 1;
		}
		boolean result = count == 0;

		response.setContentType("text/html");

		PrintWriter out = response.getWriter();

		SaleUsersLogin user = (SaleUsersLogin) request.getSession().getAttribute("user");

		if (result) {
			saleMeeting.setSaleMeetingId(saleMeetingId);
			saleMeeting.setUpdateDate(new Date());
			saleMeeting.setStartDate(DateUtil.stringToDate2(sDate));
			saleMeeting.setEndDate(DateUtil.stringToDate2(eDate));
			saleMeeting.setUpdateId(user.getSaleUsersLoginId());
			saleMeeting.setMeetingCount(Integer.parseInt(mcount));
			boolean flag = meetingServiceInner.updateMeeting(saleMeeting);
			if (flag) {
				try {
					// 保存附件
					affixService.saveAffix(affixStr, "SALEMEETING", saleMeetingId);
					add = "编辑早会成功！";
				} catch (Exception e) {
					add = "编辑早会失败！";
				}
			} else {
				add = "编辑早会失败！";
			}

		}

		/*
		 * json="{"+"result:\""+result+"\""+","+"add:\""+add+"\""+","+"newsTitle:\""
		 * +newsTitle+"\""+","+"newsContent:\""+
		 * newsContent+"\""+","+"affixPat:\""
		 * +affixPat+"\""+","+"branch:\""+branch+"\""+"}";
		 */

		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		request.setCharacterEncoding("UTF-8");


		JSONObject temp = new JSONObject();
		temp.put("result", result);
		temp.put("add", add);
		temp.put("meetingTitle", meetingTitle);
		temp.put("meetingContent", meetingContent);
		temp.put("startDate", startDate);
		temp.put("endDate", endDate);
		temp.put("meetingCount", meetingCount);

		out.print(temp.toString());
		out.flush();
		out.close();
	}

	/**
	 * 查看早会
	 * 
	 * @param saleNews
	 * @return String
	 * @throws SQLException
	 * @throws SerialException
	 */
	@RequestMapping(value = ("/inner/view"))
	public String viewInner(HttpServletRequest request, ModelMap map, HttpServletResponse response) throws Exception {
		String saleMeetingId = request.getParameter("saleMeetingId");
		SaleMeeting saleMeeting = meetingServiceInner.getMeeting(saleMeetingId);
		map.put("meeting", saleMeeting);
		// 附件列表
		List<SaleAffixItem> affixList = affixService.getAffix("SALEMEETING", saleMeetingId);
		map.put("affixList", affixList);
		return "/manage/meetings/inner/view";
	}
}
